package com.lcredu.lcrliving.commodity.service.impl;

import com.lcredu.common.util.PageUtils;
import com.lcredu.common.util.Query;
import com.lcredu.lcrliving.commodity.dao.AttrAttrgroupRelationDao;
import com.lcredu.lcrliving.commodity.dao.AttrgroupDao;
import com.lcredu.lcrliving.commodity.entity.AttrAttrgroupRelationEntity;
import com.lcredu.lcrliving.commodity.entity.AttrgroupEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.lcredu.lcrliving.commodity.dao.AttrDao;
import com.lcredu.lcrliving.commodity.entity.AttrEntity;
import com.lcredu.lcrliving.commodity.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    //装配AttrAttrgroupRelationDao
    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    /**
     * 实现接口,完成保存商品属性的同时,需要保存该基本属性和属性组的关联关系
     * <p>
     * 多表insert操作,事务控制
     */
    @Transactional
    @Override
    public void saveAttrAndRelation(AttrEntity attrEntity) {
        //1.先保存基本属性数据
        this.save(attrEntity);

        //2.保存商品属性(基本属性)和属性组的关联关系
        if (attrEntity.getAttrType() == 1 && attrEntity.getAttrId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity
                    = new AttrAttrgroupRelationEntity();

            attrAttrgroupRelationEntity.setAttrGroupId(attrEntity.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());

            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /*
    基本属性
     */
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long categoryId) {
        //1.创建QueryWrapper
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", 1);

        //2.考虑categoryId
        if (categoryId != 0) {
            queryWrapper.like("category_id", categoryId);
        }

        //3.考虑用户是否携带了key
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);//查询条件可更改

            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), queryWrapper
        );


        return new PageUtils(page);
    }

    /*
    销售属性
     */

    @Override
    public PageUtils querySalePage(Map<String, Object> params, Long categoryId) {
        //1.创建QueryWrapper
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", 0);

        //2.考虑categoryId
        if (categoryId != 0) {
            queryWrapper.like("category_id", categoryId);
        }

        //3.考虑用户是否携带了key
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);//查询条件可更改

            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), queryWrapper
        );


        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //1.根据attrgroupId去commodity_attr_attrgroup_relation表,查询关联的属性
        List<AttrAttrgroupRelationEntity> entities =
                attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrgroupId));

        //2.将entities的attrId收集到集合中->使用流式计算
        List<Long> attrIds = entities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //3.根据得到的attrIds获取对应的attrEntity
        //如果当前的attrIds为空,就没有关联任何一个属性
        if (attrIds == null || attrIds.size() == 0) {
            //如果没有关联任何一个基本属性,返回null
            return null;
        }

        //根据attrIds返回AttrEntity集合
        //[1,2,3] => 对应的AttrEntity对象集合
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);

        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 批量删除属性组-属性的关联关系
     *
     * @param attrAttrgroupRelationEntities
     */
    @Override
    public void deleteRelation(AttrAttrgroupRelationEntity[] attrAttrgroupRelationEntities) {
        attrAttrgroupRelationDao.deleteBatchRelation(Arrays.asList(attrAttrgroupRelationEntities));
    }

    /**
     * 获取某个属性组可以关联的基本属性
     * 1.如果某个基本属性已经关联了就不能再次关联
     * 2.某个属性组可以关联的基本属性必须是同一类
     */
    //装配AttrgroupDao
    @Resource
    private AttrgroupDao attrgroupDao;

    @Override
    public PageUtils getAllowRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //流式计算
        //1.通过接收的属性组id得到对应的categoryId
        AttrgroupEntity attrgroupEntity = attrgroupDao.selectById(attrgroupId);
        Long categoryId = attrgroupEntity.getCategoryId();

        //增加业务需求排除已经关联的基本属性
        //(1)先得到category的所有分组--commodity_attrgroup
        List<AttrgroupEntity> group =
                attrgroupDao.selectList(new QueryWrapper<AttrgroupEntity>().eq("category_id", categoryId));
        //获取属性组id
        List<Long> attrGroupIds = group.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());

        //(2)再到commodity_attr_attrgroup_relation去检索哪些基本属性已经关联
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities =
                attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));

        //收集从上面得到attrAttrgroupRelationEntities对应attr_id,放到集合->jdk8
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.通过得到的categoryId获取到对应的基本属性
        QueryWrapper<AttrEntity> wrapper =
                new QueryWrapper<AttrEntity>().eq("category_id", categoryId).eq("attr_type", 1);

        //(3)增加一个排除的条件
        if (attrIds != null && attrIds.size() != 0) {
            wrapper.notIn("attr_id", attrIds);
        }

        //3.因为还要支持条件查询,需要考虑携带的检索条件
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {//如果有内容
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        //进行分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), wrapper
        );
        return new PageUtils(page);

    }

}
